# 公共断言的封装
import json



from config import BASE_PATH


def common_assert(resp, exp_status, exp_descption):
    assert 200 == resp.status_code
    # 断言响应体数据
    resp_dict = resp.json()
    assert exp_status == resp_dict.get("status")
    assert exp_descption in resp_dict.get("description")


# 导包
import pymysql
import traceback  # python自带错误信息打印工具包


# 1.封装操作数据库的方法
def exe_sql(sql_str, db=None):
    # 定义两个变量，用来接收之后创建的数据库连接对象，游标对象
    conn = None
    cur = None
    try:
        # 2.创建数据库连接对象
        conn = pymysql.connect(host="121.43.169.97", port=3306, user="student", password="P2P_student_2022",
                               charset="utf8", database=db)

        # 3.创建游标对象
        cur = conn.cursor()

        # 4.在游标对象中执行SQL语句
        cur.execute(sql_str)
        # 如果是查询语句
        if sql_str.split(" ")[0].lower() == "select":
            # 返回全部查询结果
            return cur.fetchall()
        # 如果是非查询语句
        else:
            # 手动提交数据事务
            conn.commit()
            # 返回受影响的行数
            return "受影响的行数：{}".format(cur.rowcount)
    except:
        # 有异常的情况下，进行数据库事务回滚
        if conn is not None:
            conn.rollback()
        # 错误日志的打印
        traceback.print_exc()
    finally:
        # 5.关闭游标对象
        if cur is not None:
            cur.close()
        # 6.关闭数据库连接对象
        if conn is not None:
            conn.close()


# 封装清洗用户信息的方法
def clear_user_info():
    reg_mobile = "18743264321,'18743264321','18743264322','18743264323','18743264324','18743264325','18743264326','18743264321','18743264327','18743264328'"
    # 需要执行SQL语句
    sql1 = "delete i.* from mb_member_info i inner join mb_member m on m.id = i.member_id where m.phone in ({});".format(
        reg_mobile)
    sql2 = "delete l.* from mb_member_login_log l inner join mb_member m on m.id=l.member_id where m.phone in ({});".format(
        reg_mobile)
    sql3 = "delete from mb_member where phone in ({});".format(reg_mobile)
    sql4 = "delete from mb_member_register_log where phone in ({});".format(reg_mobile)
    # 调用封装操作数据库的方法，执行SQL语句
    exe_sql(sql1, "czbk_member")
    exe_sql(sql2, "czbk_member")
    exe_sql(sql3, "czbk_member")
    exe_sql(sql4, "czbk_member")


# 封装读取测试数据的方法
def read_json(filename, apiname):
    # 获取测试数据的文件路径
    file_path = BASE_PATH + "/data/" + filename + ".json"
    # 读取测试数据
    with open(file_path, encoding="utf-8") as f:
        # 将测试数据解析为字典类型
        data = json.load(f)

    # 获取指定接口的测试数据
    api_data = data.get(apiname)
    print(f"获取指定接口的测试数据,{api_data}")
    # 定义一个新的列表
    data_list = list()
    # 列表嵌套字典的测试数据转化为列表嵌套元组
    # 1.循环遍历列表嵌套字典的数据,获取每一个字典数据
    for data_dict in api_data:
        # 2将字典中的值提取出来,放到元组中
        data_tuple = tuple(data_dict.values())

        # 3.将每个元组添加到新列表中
        data_list.append(data_tuple)
    print(f"获取列表嵌套元组的测试数据:{data_list}")
    # 返回最新格式的(列表嵌套元组)的测试数据
    return data_list


if __name__ == '__main__':
    read_json("reg_login_data", "img_verify_code")
